<?php

namespace app\shop\controller;

use think\Controller;
// 引入邮箱发送类
use app\common\library\Email;

class Business extends Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->BusinessModel = model('Business.Business');
        $this->SourceModel = model('Business.Source');
        $this->RecordModel = model('Business.Record');
        $this->PayModel = model('Post.Pay');
        $this->OrderModel = model('Project.Order');
        $this->ReceiveModel = model('Coupon.Receive');
    }
    public function index()
    {
        if($this->request->isPost())
        {
            $busid=$this->request->param("busid",0,'trim');
            $business=$this->BusinessModel->find($busid);
            if(!$business)
            {
                $this->error('用户不存在,非法登录');
                exit;
            }
            $OrderCount=$this->OrderModel->where(['busid'=>$busid])->count();
            $ReceiveCount=$this->ReceiveModel->where(['busid'=>$busid,'status'=>'0'])->count();
            $business['order_count']=$OrderCount;
            $business['receive_count']=$ReceiveCount;
            //返回用户的最新信息
            unset($business['password']);
            unset($business['salt']);
            $this->success('返回用户数据',null,$business);
            exit;
        }
    }
    public function register()
    {
        if ($this->request->isPost()) {
            // 接受参数
            $mobile = $this->request->param('mobile', '', 'trim');
            $password = $this->request->param('password', '', 'trim');
            $action = $this->request->param('action', '', 'trim');
            
        
            if (empty($password)) {
                $this->error('密码不能为空');
                exit;
            }

            // 生成一个密码盐
            $salt = build_ranstr();

            //密码加密
            $password = md5($password . $salt);

            //组装数据
            $data = [
                'mobile' => $mobile,
                'nickname' => $mobile,
                'salt' => $salt,
                'password' => $password,
                'money' => 0,
                'auth' => 0,
                //认证状态
                'deal' => 0, //成交状态
            ];

            if(!empty($action))
            {
                $sourceid = $this->SourceModel->where(['name' => ['LIKE', "%家政服务%"]])->value('id');
                $data['sourceid'] = $sourceid;
            }else
            {
                //找出客户来源
                $sourceid = $this->SourceModel->where(['name' => ['LIKE', "%家居商城%"]])->value('id');
                $data['sourceid'] = $sourceid;
            }

            $result = $this->BusinessModel->validate('common/Business/Business')->save($data);

            //插入失败
            if ($result === FALSE) {
                //错误信息可以让模型返回出来
                $this->error($this->BusinessModel->getError());
                exit;
            } else {
                //插入成功,跳转到登录界面
                $this->success('注册成功', '/login');
                exit;
            }
        }
    }
    public function login()
    {
        if ($this->request->isPost()) {
            $mobile = $this->request->param('mobile', '', 'trim');
            $password = $this->request->param('password', '', 'trim');
            //查询用户是否存在
            $business = $this->BusinessModel->where(['mobile' => $mobile])->find();

            if (!$business) {
                $this->error('用户不存在');
                exit;
            }
            if (md5($password . $business['salt']) != $business['password']) {
                $this->error('密码不正确');
                exit;
            }
            unset($business['password']);
            unset($business['salt']);

            $this->success('登录成功','/business/index',$business);
            exit;
        }
    }
    public function check()
    {
        if($this->request->isPost())
        {
            $id = $this->request->param('id', 0, 'trim');
            $mobile = $this->request->param('mobile', 0, 'trim');

            //封装条件
            $where = [
                'id' => $id,
                'mobile' => $mobile
            ];

            // 查询
            $business = $this->BusinessModel->where($where)->find();

            if(!$business)
            {
                $this->error('用户不存在，非法登录', '/login');
                exit;
            }

            //返回用户的最新信息
            unset($business['password']);
            unset($business['salt']);

            $this->success('查询用户成功', null, $business);
            exit;
        }

    }
    public function profile()
    {
        if($this->request->isPost())
        {
            $id = $this->request->param('id', 0, 'trim');
            $region = $this->request->param('region', '', 'trim');
            $password = $this->request->param('password', '', 'trim');
            $email = $this->request->param('email', '', 'trim');
            $params = $this->request->param();

            // 查询
            $business = $this->BusinessModel->find($id);

            if(!$business)
            {
                $this->error('用户不存在，非法登录');
                exit;
            }

            //判断密码是否为空
            if(!empty($password))
            {
                $salt = build_ranstr();

                $params['salt'] = $salt;
                $params['password'] = md5($password.$salt);
            }

            //修改了邮箱
            if($email != $business['email'])
            {
                $params['auth'] = '0';
            }

            //地区
            if(!empty($region))
            {
                //获取地区路径
                $parent = model('Region')->where(['code' => $region])->value('parentpath');

                //转换为数组
                $list = explode(',', $parent);

                if(isset($list[0]))
                {
                    $params['province'] = $list[0];
                }else
                {
                    $params['province'] = null;
                }

                if(isset($list[1]))
                {
                    $params['city'] = $list[1];
                }else
                {
                    $params['city'] = null;
                }

                if(isset($list[2]))
                {
                    $params['district'] = $list[2];
                }else
                {
                    $params['district'] = null;
                }
            }
            // var_dump($_FILES['avatar']);
            // exit;
            //判断是否有图片上传
            if(isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0)
            {
                $result = build_upload('avatar');
                if($result['code'])
                {
                    $params['avatar'] = $result['data'];
                }else
                {
                    $this->error($result['msg']);
                    exit;
                }
            }

            //更新数据
            $result = $this->BusinessModel->validate('common/Business/Business')->isUpdate(true)->save($params);

            //判断是否有更新成功
            if($result === FALSE)
            {
                $this->error($this->BusinessModel->getError());
                exit;
            }
            
            // 判断是否有旧图片
            if(isset($params['avatar']))
            {
                $avatar = $business['avatar'];
                is_file(".".$avatar) && unlink(".".$avatar);
            }

            //重新查一遍
            $update = $this->BusinessModel->find($id);

            unset($update['password']);
            unset($update['salt']);

            $this->success('基本资料修改成功', null, $update);
            exit;
        }
    }

    //发送邮件的方法
    public function email()
    {
        if($this->request->isPost())
        {
            // $params=$this->request->param();
            $receiver = $this->request->param('email') ? $this->request->param('email') : '';
            // var_dump($receiver);
            // exit;
            if(empty($receiver))
            {
                $this->error('邮箱地址为空');
                exit;
            }
            // var_dump($params);
            // exit;
            $Ems = model('Ems');
            //判断是否有发送过验证码
            $where = [
                'event' => 'email',
                'email' => $receiver,
                'times' => 0
            ];
            $check = $Ems->where($where)->find();

            if($check)
            {
                $this->error('已重复发送验证码');
                exit;
            }
            //验证码
            $code = build_ranstr(5);
            // 插入到数据表中
            $data = [
                'event' => 'email',
                'email' => $receiver,
                'code' => $code,
                'times' => 0,
            ];

            //开启事务操作
            $Ems->startTrans();

            //插入
            $res = $Ems->save($data);

            //插入失败
            if(!$res)
            {
                $this->error('验证码插入失败');
                exit;
            }

            //实例化邮箱对象
            $email = new Email;

            $html = "<div>您的邮箱认证码为：<b>$code</b></div>";

            //获取系统配置
            $config = [
                'mail_type' => config('site.mail_type'),
                'mail_smtp_host' => config('site.mail_smtp_host'),
                'mail_smtp_port' => config('site.mail_smtp_port'),
                'mail_smtp_user' => config('site.mail_smtp_user'),
                'mail_smtp_pass' => config('site.mail_smtp_pass'),
                'mail_verify_type' => config('site.mail_verify_type'),
                'mail_from' => config('site.mail_from'),
            ];
            //合并系统配置
            \think\Config::set('site', array_merge(\think\Config::get('site'), $config));

            //发送邮件
            $result = $email->to($receiver)
                ->subject(config('site.name')."邮箱认证")
                ->message($html)
                ->send();

            if($result)
            {
                //事务提交
                $Ems->commit();
                $this->success('发送验证码成功，请注意查收');
                exit;
            }else
            {
                //回滚验证码
                $Ems->rollback();
                $this->error($email->getError());
                exit;
            }
        }
    }

    //邮箱验证方法
    public function checkEmail()
    {
        if($this->request->isPost())
        {
            $id = $this->request->param('id',0,'trim');
            $email = $this->request->param('email','','trim');
            $code = $this->request->param('code', '', 'trim');

            $where = [
                'event' => 'email',
                'email' => $email,
                'code' => $code,
            ];

            //加载模型
            $EmsModel = model('Ems');
            $BusinessModel = model('Business.Business');

            //开启事务
            $EmsModel->startTrans();
            $BusinessModel->startTrans();

            //数据查询
            $row = $EmsModel->where($where)->find();

            if(!$row)
            {
                $this->error('邮箱认证码有误，请重新输入');
                exit;
            }

            //更新用户状态
            $data = [
                'id' => $id,
                'auth'=>'1'
            ];

            $BusinessStatus = $BusinessModel->isUpdate(true)->save($data);

            if($BusinessStatus === FALSE)
            {
                $this->error('邮箱认证失败');
                exit;
            }

            //删除邮箱验证码
            $EmsStatus = $EmsModel->destroy($row['id']);

            if($EmsStatus === FALSE)
            {
                $BusinessModel->rollback();
                $this->error('删除邮箱认证码失败');
                exit;
            }

            if($BusinessStatus === FALSE || $EmsStatus === FALSE)
            {
                $EmsModel->rollback();
                $BusinessModel->rollback();
                $this->error('认证失败');
                exit;
            }else
            {
                //提交事务
                $BusinessModel->commit();
                $EmsModel->commit();
                $this->success("邮箱认证成功",null,'');
                exit;
            }
        }
    }

    // 查询消费记录
    public function record()
    {
        $busid=$this->request->param("busid",0,'trim');
        $page=$this->request->param("page",0,'trim');
        $limit=10;
        $start=($page-1)*$limit;
        $business=$this->BusinessModel->find($busid);
        if(!$business)
        {
            $this->error('用户不存在');
            exit;
        }
        $where=[
            'busid'=>$business->id,
        ];
        $record=$this->RecordModel->where($where)->order('id','asc')->limit($start,$limit)->select();
        if(count($record)<=0)
        {
            $this->error('暂无更多数据',null,$record);
            exit;
        }else
        {
            $this->success('返回数据成功',null,$record);
            exit;
        }
    }

    // 查询充值记录
    public function pay()
    {
        if($this->request->isPost())
        {
            $busid=$this->request->param("busid",0,'trim');
            $page=$this->request->param("page",0,'trim');
            $limit=10;
            $start=($page-1)*$limit;
            $business=$this->BusinessModel->find($busid);
            if(!$business)
            {
                $this->error('用户不存在');
                exit;
            }
            $where=[
                'busid'=>$business->id,
            ];
            $pay=$this->PayModel->where($where)->order('id','asc')->limit($start,$limit)->select();
            if(count($pay)<=0)
            {
                $this->error('暂无更多数据',null,$pay);
                exit;
            }else
            {
                $this->success('返回数据成功',null,$pay);
                exit;
            }
        }
    }
    
}